<template>
  <div class="goodList">
    <HeadInfo></HeadInfo>
    <div class="screen">
      <search-form :classifyList="classifyList" @search="search" @reset="reset">
      </search-form>
    </div>
    <a-card :bordered="true" :loading="loading">
      <div
        :class="['search-head', layout, pageWidth]"
        style="width: 100%; margin: 10px auto; overflow: hidden"
      >
        <div class="search-input">
          <a-input-search
            class="search-ipt"
            style="width: 300px; float: right"
            placeholder="请输入..."
            size="large"
            enterButton="搜索"
            v-model="searchContent"
            @search="getGoods"
          />
        </div>
      </div>
      <a-empty v-show="!data.length" />
      <a-list
        itemLayout="vertical"
        size="large"
        style="margin-top: 10px"
        :key="item.key"
        v-for="item in data"
        :bordered="true"
      >
        <a-list-item :bordered="true">
          <a-list-item-meta :title="`商品: ${item.name}`">
            <div slot="description">
              <a-tag>商品ID:{{ item.id }}</a-tag>
              <a-tag>分类ID:{{ item.classify_id }}</a-tag>
              <a-tag>项目ID:{{ item.project_id }}</a-tag>
              <a-tag
                :color="
                  item.status == 0
                    ? 'volcano'
                    : item.status == 1
                    ? 'green'
                    : 'red'
                "
              >
                {{
                  item.status == 0
                    ? '商品已下架'
                    : item.status == 1
                    ? '商品上架中'
                    : '商品已删除'
                }}
              </a-tag>
              <a-tag
                v-show="item.status == 2"
                class="recover"
                :color="'#87d068'"
                @click="stats(item)"
                >恢复</a-tag
              >
              <em>添加时间:{{ item.createdAt }}</em>
              <a-divider orientation="left"></a-divider>
              <a-tag color="cyan">商品图片:</a-tag>
              <a-avatar
                class="photo"
                shape="square"
                :size="70"
                v-for="ele in item.s_goods_photos"
                :key="ele.id"
                slot="avatar"
                :src="ele.path"
                style="margin: 0 2px; border: 1px dashed #2db7f5"
                @click="preview(ele.path)"
              />
            </div>
          </a-list-item-meta>
          <div class="content">
            <div class="desc">
              <a-tag color="cyan">商品描述:</a-tag>
              <p>{{ item.desc }}</p>
            </div>
            <div class="detail">
              <a-tag color="cyan" style="align-self: flex-start"
                >商品详情:</a-tag
              >
              <a-collapse :bordered="false" style="background: #fff">
                <a-collapse-panel style="border: none">
                  <span
                    v-html="
                      item.rich_text
                        ? item.rich_text
                        : '这家伙很懒,商品详情都没有留下'
                    "
                  ></span>
                </a-collapse-panel>
              </a-collapse>
            </div>
          </div>
          <span slot="actions" style="color: orange">
            <a-icon style="margin-right: 8px" type="pay-circle" />售价:{{
              item.price
            }}
          </span>
          <span slot="actions">
            <a-icon style="margin-right: 8px" type="money-collect" />优惠价:{{
              item.sale_price
            }}
          </span>
          <span slot="actions">
            <a-icon style="margin-right: 8px" type="bank" />库存:{{
              item.stock_num
            }}
          </span>
          <div slot="actions">
            <a
              @click="openSku(item)"
              style="margin-right: 8px"
              v-if="item.status != 2"
            >
              <a-icon type="edit" />商品规格
            </a>
            <a
              @click="edit(item)"
              style="margin-right: 8px"
              v-if="item.status != 2"
            >
              <a-icon type="edit" />编辑
            </a>
            <a
              @click="stats(item)"
              style="margin-right: 8px"
              v-if="item.status != 2"
            >
              <a-icon :type="item.status == 0 ? 'caret-up' : 'caret-down'" />{{
                item.status == 0 ? '上架商品' : '下架商品'
              }}
            </a>
            <a
              @click="notice(item)"
              style="margin-right: 8px"
              v-if="item.status != 2"
            >
              <a-icon type="delete" />删除
            </a>
          </div>
        </a-list-item>
      </a-list>
      <a-pagination
        showSizeChanger
        :default-current="current"
        :defaultPageSize="pageSize"
        :total="total"
        :showTotal="() => `共${showTotal}条`"
        v-show="data.length"
        @change="pageChange"
        @showSizeChange="showSizeChange"
        style="margin: 10px auto; float: right"
      />
    </a-card>
    <a-drawer
      v-if="visible"
      title="修改商品信息"
      :width="900"
      :visible.sync="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <goodsInfo :info="info" @close="onClose"></goodsInfo>
    </a-drawer>
    <!-- 添加或修改规格抽屉 -->
    <a-drawer
      v-if="skuVisible"
      title="新增或修改商品规格"
      :width="800"
      :visible.sync="skuVisible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <h3 style="margin: 10px 0">你选择的规格是:</h3>
      <a-checkbox-group
        v-model="checkList"
        :options="list"
        @change="checkChange"
      />
      <h3 style="margin: 10px 0">库存及价格:</h3>
      <a-button
        type="primary"
        class="editable-add-btn"
        @click="handleAdd"
        style="margin-bottom: 8px"
        >添加规格</a-button
      >
      <a-table
        bordered
        :data-source="dataSource"
        :columns="columns"
        :pagination="false"
        :rowKey="
          (record, index) => {
            return index;
          }
        "
      >
        <template slot="goods_specs" slot-scope="text, record">
          <div v-for="(item, index) in record.goods_specs" :key="index">
            <!-- {{ item.sku }} -->
            <a-cascader
              style="margin: 8px 0"
              v-model="item.sku"
              :options="options"
              placeholder="Please select"
            />
            <span
              style="
                margin-left: 5px;
                border: 1px solid black;
                border-radius: 50%;
                padding: 3px;
                color: inherit;
              "
            >
              <a-icon type="minus" @click="delKey(item, index, record)" />
            </span>
          </div>

          <a-button @click="addKey(record)">
            <a-icon type="plus" />
          </a-button>
        </template>
        <template slot="goods_stock" slot-scope="text, record">
          <div class="editable-cell">
            <a-input v-model="record.goods_stock" />
          </div>
        </template>
        <template slot="goods_price" slot-scope="text, record">
          <div class="editable-cell">
            <a-input v-model="record.goods_price" />
          </div>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-popconfirm
            v-if="dataSource.length"
            title="Sure to delete?"
            @confirm="onDelete(record.id, record.key)"
          >
            <a>Delete</a>
          </a-popconfirm>
        </template>
      </a-table>
      <a-button @click="confirmSku" style="margin: 8px" type="primary"
        >确定</a-button
      >
      <a-button class="editable-add-btn" style="margin: 8px" @click="cancel"
        >取消</a-button
      >
    </a-drawer>
    <a-modal
      v-model="showModal"
      title="温馨提示"
      ok-text="确认"
      cancel-text="取消"
      @ok="deleteRecord"
    >
      确认删除要"{{ info.name }}"吗?
    </a-modal>
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleCancel"
      :zIndex="1001"
    >
      <img alt="example" style="width: 95%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import SearchForm from '@/pages/components/form/SearchForm';
import goodsInfo from '@/pages/components/addOrEdit/addOrEdit';
import HeadInfo from '@/pages/components/detail/HeadInfo';
import { mapState } from 'vuex';
import {
  goodsList,
  deleteGood,
  updateGood,
  goodsClassify,
  searchGood,
} from '@/services/shopApi/dataSource';
import { userinfo } from '@/services/user';
import { getKeyValue, getSku, addSku, delSku } from '@/services/shopApi/sku';

import { projectsList } from '@/services/project';
import moment from 'moment';
export default {
  name: 'goodsList',
  async created() {
    let res = await userinfo();
    this.projectId = res.result.project_id;
    this.getSkuList();
    // 获取所属分类
    this.getGoodsClassify(this.projectId);
    this.loading = true;
    //放入缓存减少请求量
    if (sessionStorage.getItem('projectsList')) {
      this.projectsList = JSON.parse(sessionStorage.getItem('projectsList'));
    } else {
      this.getProjectsList();
    }
    if (sessionStorage.getItem('goodsList')) {
      this.data = JSON.parse(sessionStorage.getItem('goodsList'));
      this.showTotal = Number(sessionStorage.getItem('total'));
      this.total = Number(sessionStorage.getItem('total'));
      if (sessionStorage.getItem('pagination')) {
        this.pageSize = Number(
          JSON.parse(sessionStorage.getItem('pagination')).limit
        );
        this.current = Number(
          JSON.parse(sessionStorage.getItem('pagination')).page
        );
      }
      this.loading = false;
    } else {
      this.getGoodList();
    }
  },
  data() {
    return {
      data: [],
      projectId: 0,
      checkList: [],
      list: [],
      dataList: [],
      value: [],
      keyList: [],
      checkValue: [],
      options: [],
      sVisible: false,
      columns: [
        {
          title: '规格属性',
          dataIndex: 'goods_specs',
          width: '43%',
          scopedSlots: {
            customRender: 'goods_specs',
          },
        },
        {
          title: '库存',
          dataIndex: 'goods_stock',
          scopedSlots: {
            customRender: 'goods_stock',
          },
        },
        {
          title: '价格',
          dataIndex: 'goods_price',
          scopedSlots: {
            customRender: 'goods_price',
          },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: {
            customRender: 'operation',
          },
        },
      ],
      dataSource: [
        // {
        //   key: 1,
        //   goods_price: 300,
        //   goods_stock: 400,
        //   goods_specs: [],
        //   // goods_specs: [{ sku: ["1", "11"] }, { sku: ["2", "21"] }],
        // },
      ],
      previewVisible: false,
      previewImage: '',
      loading: false,
      showTotal: '',
      total: 0,
      pageSize: 10,
      current: 1,
      //sku抽屉
      skuVisible: false,
      //商品信息抽屉
      visible: false,
      info: {},
      showModal: false,
      projectsList: [],
      classifyList: [],
      searchContent: '',
    };
  },
  methods: {
    cancel() {
      this.skuVisible = false;
    },
    checkChange(checkedValue) {
      let arr = [];
      for (let i = 0; i < checkedValue.length; i++) {
        this.dataList.forEach((ele) => {
          if (checkedValue[i] === ele.keyName) {
            arr.push({
              value: ele.id,
              label: ele.keyName,
              children: ele.s_attributesValues.map((ele) => {
                return {
                  value: ele.id,
                  label: ele.attribute_value,
                };
              }),
            });
          }
        });
      }
      this.options = arr;
    },
    delKey(item, index, record) {
      this.dataSource.forEach((ele) => {
        if (record === ele) {
          ele.goods_specs.splice(index, 1);
        }
      });
    },
    addKey(record) {
      record.goods_specs.push({});
    },
    async confirmSku() {
      let arr = [];
      let goodsarr = [];
      this.dataSource.forEach((ele) => {
        goodsarr.push({
          id: ele.id,
          goods_stock: ele.goods_stock,
          goods_price: ele.goods_price,
          goods_specs: [],
        });
        ele.goods_specs.forEach((ele) => {
          arr.push(ele.sku[0]);
        });
      });
      goodsarr.forEach((item) => {
        this.dataSource.forEach((ele) => {
          if (ele.id === item.id) {
            ele.goods_specs.forEach((ele) => {
              item.goods_specs.push(ele.sku[1]);
            });
          }
        });
      });
      let obj = {
        goods_id: this.info.id,
        goods_keys: [...new Set(arr)].join(','),
        goodarr: goodsarr.map((ele) => {
          return {
            id: ele.id,
            goods_specs: ele.goods_specs.join(','),
            goods_stock: ele.goods_stock,
            goods_price: ele.goods_price,
          };
        }),
      };
      await addSku(obj);
      this.skuVisible = false;
    },
    async onDelete(id) {
      this.dataSource = this.dataSource.filter((item) => item.id !== id);
      await delSku(id);
      this.getSkuList();
    },
    handleAdd() {
      const newData = {
        id: this.count,

        goods_price: 0,
        goods_stock: 0,
        goods_specs: [],
      };
      this.dataSource.push(newData);
    },
    //获取规格
    async getSkuList() {
      let res = await getKeyValue({ project_id: this.projectId });
      this.dataList = res.result;
      this.keyList = res.result.map((ele) => ({
        label: ele.keyName,
        value: ele.keyName,
      }));
      this.list = res.result.map((ele) => ({
        label: ele.keyName,
        value: ele.keyName,
      }));
    },
    async openSku(info) {
      const finalArr = [];
      this.info = info;
      this.skuVisible = true;
      try {
        let res = await getSku({ id: info.id });
        let stock_list = res.result.stock_list;
        let checkList = res.result.property;
        if (stock_list) {
          this.checkList = checkList.map((ele) => ele.keyName);
          let arr = [];
          for (let i = 0; i < checkList.length; i++) {
            this.dataList.forEach((ele) => {
              if (checkList[i].keyName === ele.keyName) {
                arr.push({
                  value: ele.id,
                  label: ele.keyName,
                  children: ele.s_attributesValues.map((ele) => {
                    return {
                      value: ele.id,
                      label: ele.attribute_value,
                    };
                  }),
                });
              }
            });
          }
          this.options = arr;
          const object = {};
          checkList.forEach(({ id, s_attributesValues: attr }) => {
            object[id] = attr.map((item) => item.id);
          });
          stock_list.forEach((values) => {
            const finalObject = {
              id: values.id,
              goods_price: values.goods_price,
              goods_stock: values.goods_stock,
            };
            const specs = values.goods_specs.split(',');
            const arr = [];
            specs.forEach((value) => {
              Object.keys(object).forEach((key) => {
                const isInclude = object[key].includes(+value);
                if (isInclude) {
                  arr.push({ sku: [+key, +value] });
                }
              });
            });
            finalObject.goods_specs = arr;
            finalArr.push(finalObject);
          });
          this.dataSource = finalArr;
        }
      } catch (error) {
        this.$message.error(error.msg);
      }
    },
    preview(src) {
      this.previewVisible = true;
      this.previewImage = src;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async getGoods(value) {
      try {
        const data = await searchGood({ name: value });
        this.data = data.result.rows;
      } catch (error) {
        this.$message.error(error);
      }
    },
    search(params) {
      this.loading = true;
      goodsList(params)
        .then((res) => {
          this.showTotal = res.result.count;
          this.total = res.result.count;
          this.data = res.result.rows.map((res) => {
            res.key = res.id;
            res.createdAt = moment(res.createdAt).format(
              'YYYY-MM-DD  HH:mm:ss'
            );
            return res;
          });
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error(err);
        });
    },
    getProjectsList() {
      projectsList().then((res) => {
        this.projectsList = res.result;
        sessionStorage.setItem('projectsList', JSON.stringify(res.result));
        this.loading = false;
      });
    },
    stats(item) {
      this.loading = true;
      if (item.status == 0) {
        item.status = 1;
        updateGood(item)
          .then((res) => {
            this.$message.success(res.msg);
            this.getGoodList();
            this.loading = false;
          })
          .catch((error) => {
            this.$message.error(error.msg);
          });
      } else if (item.status == 2) {
        item.status = 0;
        updateGood(item)
          .then((res) => {
            this.$message.success(res.msg);
            this.getGoodList();
            this.loading = false;
          })
          .catch((error) => {
            this.$message.error(error.msg);
          });
      } else {
        item.status = 0;
        updateGood(item)
          .then((res) => {
            this.$message.success(res.msg);
            this.getGoodList();
            this.loading = false;
          })
          .catch((error) => {
            this.$message.error(error.msg);
          });
      }
    },
    notice(item) {
      this.info = item;
      this.showModal = true;
    },
    deleteRecord() {
      this.loading = true;
      deleteGood(this.info.id)
        .then((res) => {
          this.$message.success(res.msg);
          this.getGoodList();
          this.showModal = false;
          this.loading = false;
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
    edit(info) {
      this.info = info;
      this.visible = true;
    },
    onClose() {
      this.visible = false;
      this.skuVisible = false;
      this.info = {};
      this.loading = true;
      this.getGoodList();
    },
    pageChange(pageNumber, pageSize) {
      this.loading = true;
      this.current = pageNumber;
      let params = {};
      params.page = pageNumber;
      params.limit = pageSize;
      sessionStorage.setItem('pagination', JSON.stringify(params));
      this.getGoodList(params);
    },
    showSizeChange(current, size) {
      this.loading = true;
      let params = {};
      this.pageSize = size;
      params.page = current;
      params.limit = size;
      sessionStorage.setItem('pagination', JSON.stringify(params));
      this.getGoodList(params);
    },
    //重置更新
    reset() {
      this.loading = true;
      this.classifyList = [];
      //   this.projectsList = [];
      if (sessionStorage.getItem('goodsList')) {
        this.data = JSON.parse(sessionStorage.getItem('goodsList'));
        this.showTotal = Number(sessionStorage.getItem('total'));
        this.total = Number(sessionStorage.getItem('total'));
        if (sessionStorage.getItem('pagination')) {
          this.pageSize = Number(
            JSON.parse(sessionStorage.getItem('pagination')).limit
          );
          this.current = Number(
            JSON.parse(sessionStorage.getItem('pagination')).page
          );
        }
        this.loading = false;
      } else {
        this.getGoodList();
      }
    },
    //请求
    getGoodList(params) {
      goodsList(params)
        .then((res) => {
          this.showTotal = res.result.count;
          this.total = res.result.count;
          this.data = res.result.rows.map((res) => {
            res.key = res.id;
            res.createdAt = moment(res.createdAt).format(
              'YYYY-MM-DD  HH:mm:ss'
            );
            return res;
          });
          sessionStorage.setItem('total', res.result.count);
          sessionStorage.setItem('goodsList', JSON.stringify(this.data));
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error(err);
        });
    },

    getGoodsClassify(id) {
      goodsClassify({ project_id: id })
        .then((res) => {
          const data = res.result;
          // 序列化时间
          this.classifyList = data;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
  },
  computed: {
    count() {
      return this.dataSource.length;
    },
    ...mapState('account', { currUser: 'user' }),
    ...mapState('setting', ['layout', 'pageWidth']),
  },
  components: {
    SearchForm,
    goodsInfo,
    HeadInfo,
  },
};
</script>

<style lang="less" scoped>
.ant-list-item {
  margin-bottom: 20px !important;
}
.extra {
  width: 272px;
  height: 1px;
}
em {
  color: @disabled-color;
  font-style: normal;
  margin-left: 16px;
}
.content {
  .desc {
    display: flex;
    justify-content: left;
    align-items: top;
    margin-bottom: 2px;
    p {
      margin: 0 0;
    }
  }
  .detail {
    display: flex;
    justify-content: left;
    align-items: top;
    line-height: 22px;
    max-width: 720px;
  }
}
.search-head {
  background-color: @base-bg-color;
  margin: -24px;
  &.head.fixed {
    margin: -24px 0;
  }
  .search-input {
    text-align: center;
  }
}
.search-content {
  margin-top: 48px;
}
.recover:hover {
  cursor: pointer;
}
.photo:hover {
  cursor: pointer;
}
</style>
